package top.tangyh.lamp.care.controller;

import com.google.gson.Gson;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import top.tangyh.lamp.care.common.BPatientToFuerInpatientConverter;
import top.tangyh.lamp.care.mqtt.send.SendMqtt;
import top.tangyh.lamp.care.mqtt.send.dto.Msg;
import top.tangyh.lamp.care.properties.MqttProperties;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.tangyh.basic.base.R;
import top.tangyh.lamp.care.entity.BPatient;
import top.tangyh.lamp.care.service.BDevBindService;
import top.tangyh.lamp.care.service.BDevDetailService;
import top.tangyh.lamp.care.service.BPatientService;
import top.tangyh.lamp.care.vo.result.BDevDetailResultVO;
import top.tangyh.lamp.care.vo.result.BPatientResultVO;
import top.tangyh.lamp.care.vo.result.FuerInpatientInfoResult;
import top.tangyh.lamp.care.vo.result.PatientBindOutputVO;
import top.tangyh.lamp.care.vo.save.BindInVO;
import top.tangyh.lamp.care.vo.save.UnBindInVO;
import top.tangyh.lamp.common.utils.IcuDateUtils;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author: zqb
 * 设备信息接口、病人信息接口、病人设备绑定接口  解绑接口
 * @date: 2024/8/23 16:08
 */
@Slf4j
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/pda")
@Tag(name = "PDA绑定相关接口")
public class PdaBindController {

    private final BPatientService bPatientService;

    private final BDevDetailService devDetailService;

    private final BDevBindService bindService;

    private final MqttProperties mqttProperties;

//    @Autowired
//    private Environment environment;

//    @Operation(summary = "查询单病人基本信息")
//    @PostMapping("/patient/one/detail")
//    public R<BPatientResultVO> selectPatient(String hospitalNumber) {
//        BPatientResultVO bPatientResultVO = bPatientService.selectOneByQuery(hospitalNumber);
//
//        List<PatientBindOutputVO> patientBindOutputVO = bindService.queryPatientBind(hospitalNumber);
//        bPatientResultVO.setPatientBindOutputVO(patientBindOutputVO);
//
//        return R.success(bPatientResultVO);
//    }

    @Operation(summary = "查询单病人基本信息")
    @PostMapping("/patient/one/detail")
    public R<FuerInpatientInfoResult> selectPatientOne(String hospitalNumber) {

        BPatientResultVO bPatientResultVO= bPatientService.selectOneByQuery(hospitalNumber);
        FuerInpatientInfoResult fuerInpatientInfoResult=BPatientToFuerInpatientConverter.convert(bPatientResultVO);
       return R.success(fuerInpatientInfoResult);
//        TestWebservice testWebservice = new TestWebservice();
//        //webservice数据
//        List<FuerInpatientInfoResult> list;
//        list = testWebservice.analysisData();
//
//        FuerInpatientInfoResult fuerInpatientInfoResult=bPatientService.getPatientInfo(hospitalNumber,list);
//        TestWebservice testWebservice = new TestWebservice();
//        //webservice数据
//        List<FuerInpatientInfoResult> list;
//        list = testWebservice.analysisData();
//        List<FuerInpatientInfoResult>  fuerInpatientInfoResults=bPatientService.getHomePatients(list);
        //fuerInpatientInfoResults.sort(Comparator.comparing(FuerInpatientInfoResult::getBedNo));
//        Optional<FuerInpatientInfoResult> uniquePatient =
//                fuerInpatientInfoResults.stream()
//                        .filter(patient -> hospitalNumber.equals(patient.getInpatientId()))
//                        .findFirst();

//        if (uniquePatient.isPresent()) {
//            FuerInpatientInfoResult patientInfo = uniquePatient.get();
//            return R.success(patientInfo);
//            // 对 patientInfo 进行处理
//        } else {
//            // 未找到对应的患者信息
//            return R.fail("未找到患者信息");
//        }


    }


    @Operation(summary = "单个设备基本信息查询")
    @GetMapping("/devDetail/one")
    public R<BDevDetailResultVO> selectDevDetail(@RequestParam String devCode) {
        int count=devDetailService.getCountByDevCode(devCode);
        if(count>1){
            return R.fail("该设备识别号存在重复，重复记录"+count);
        }
        if(count==0){
            return R.fail("该设备尚未录入系统，请联系相关人员添加");
        }
        BDevDetailResultVO devDetailResultVO = devDetailService.selectOneQuery(devCode);

//        BPatient bPatient=bindService.selectPatientByDevCode(devDetailResultVO.getDevCode());
//        BPatient bPatient = Optional.ofNullable(devDetailResultVO)
//                .map(BDevDetailResultVO::getDevCode)  // 获取 devCode，如果 devDetailResultVO 为 null，则跳过
//                .map(bindService::selectPatientByDevCode)  // 如果 devCode 不为空，调用 bindService
//                .orElse(null);  // 如果 devCode 为空或任何步骤为空，则返回 null

//        devDetailResultVO.setBPatientResultVO(bPatient);
//        Optional.ofNullable(devDetailResultVO)
//                .ifPresent(vo -> vo.setBPatientResultVO(bPatient));

        return R.success(devDetailResultVO);
    }

//    @Operation(summary = "绑定")
//    @PostMapping("/bind")
//    public R bind(@RequestBody @Valid BindInVO bindInVO) {
//        bindService.bind(bindInVO);
//        return R.success();
//    }

    @Operation(summary = "绑定")
    @PostMapping("/bind")
    public R bind(String hospitalNumber, String devCode) {
        BindInVO bindInVO = new BindInVO();
        bindInVO.setHospitalNumber(hospitalNumber);
        bindInVO.setDevCode(devCode);

//        FuerInpatientInfoResult fuerInpatientInfoResult= this.selectPatientOne(hospitalNumber).getData();
//        TestWebservice testWebservice = new TestWebservice();
//        //webservice数据
//        List<FuerInpatientInfoResult> list;
//        list = testWebservice.analysisData();
//        FuerInpatientInfoResult fuerInpatientInfoResult=bPatientService.getPatientInfo(hospitalNumber,list);
        bindService.bind(bindInVO);

        //推送mqtt消息 通知前端刷新页面
//        String hostUrl = environment.getProperty("lamp.mqtt5.hostUrl");
//        MqttProperties mqttProperties=new MqttProperties();
        //String content, String topic,String MQTT_BROKER,
        //                                  String clientId,String USERNAME,String PASSWORD
        Msg msg = new Msg();
        msg.setRefresh(1);
        msg.setType(2);
        msg.setSendTime(IcuDateUtils.getGivenZoneTimeStr(LocalDateTime.now()));

        Gson gson = new Gson();
        String content = gson.toJson(msg);

        System.out.println(mqttProperties.getUsername());
        SendMqtt.sendToMQTT(content, mqttProperties.getDefaultTopic(), mqttProperties.getHostUrl(),
                mqttProperties.getClientId(), mqttProperties.getUsername(), mqttProperties.getPassword());

        return R.success();
    }

    @Operation(summary = "解绑")
    @PutMapping("/unbind")
    public R unBind(String hospitalNumber, String devCode) {
        UnBindInVO unBindInV = new UnBindInVO();
        unBindInV.setHospitalNumber(hospitalNumber);
        unBindInV.setDevCode(devCode);

//        FuerInpatientInfoResult fuerInpatientInfoResult= this.selectPatientOne(hospitalNumber).getData();
//        TestWebservice testWebservice = new TestWebservice();
//        //webservice数据
//        List<FuerInpatientInfoResult> list;
//        list = testWebservice.analysisData();
//        FuerInpatientInfoResult fuerInpatientInfoResult=bPatientService.getPatientInfo(hospitalNumber,list);
        bindService.unBind(unBindInV);

        //推送mqtt消息 通知前端刷新页面
        Msg msg = new Msg();
        msg.setRefresh(1);
        msg.setType(2);
        msg.setSendTime(IcuDateUtils.getGivenZoneTimeStr(LocalDateTime.now()));

        Gson gson = new Gson();
        String content = gson.toJson(msg);

        System.out.println(mqttProperties.getUsername());
        SendMqtt.sendToMQTT(content, mqttProperties.getDefaultTopic(), mqttProperties.getHostUrl(),
                mqttProperties.getClientId(), mqttProperties.getUsername(), mqttProperties.getPassword());
        return R.success();
    }
}
